import React, {Component} from 'react';
import { NavLink } from 'react-router-dom';
import { Card,Button,Table,Modal,Typography, message} from 'antd';
import "./style.css";
//网络请求
import {getDataList, deleteArticleByID} from "../../../services";
//数据处理
import {createColumns, exportExcel} from "../../../utils";


const ButtonGroup = Button.Group;

class ArticleList extends Component {
    constructor(props) {
        super(props);

        this.state = {
            total : 0,
            list: [],
            columns: [],
            isLoading: false,
            offset:0,
            limited: 10,
            deleteArticleTitle:'',
            isShowArticleModal:false,
            deleteArticleConfirmLoading:false,
            deleteArticleID:null
        }
    }
    
    //删除文章按钮
    showDeleteArticleModal = (record) => {
    //使用函数式方式调用
    //     // console.log(recotd.id);
    //     //1.弹窗
    //     Modal.confirm({
    //         content:`此操作不可逆，请谨慎?`,
    //         title: `确认要删除《${record.title}》?`,
    //         okText:'别墨迹，删除了',
    //         cancelText:'朕再想想',
    //         onOk(){
    //             deleteArtticle(record.id)
    //             .then(res => {
    //                 console.log(res);
    //             })
    //         } 
    //     })
    //     //2.当点击ok时发送删除的请求
    // }

    //使用组件方式完成
    this.setState({
        isShowArticleModal:true,
        deleteArticleTitle:record.title,
        deleteArticleID: record.id
        
    })
    }
    //删除隐藏弹窗
    hideDeleteModal = () => {
        this.setState({
            isShowArticleModal:false,
            deleteArticleTitle:'',
            deleteArticleConfirmLoading:false
            
        })
    }
    //点击弹窗确认按钮所要进行的事件
    deleteArticle = () => {
        // console.log(this.state.deleteArticleID);   //获取到当前删除数据的ID
        this.setState({
            deleteArticleConfirmLoading:true
        })
        deleteArticleByID().then((res) =>{
            console.log(res);  //返回数据是状态码和Msg
            // 如果返回的状态码是200，表示删除成功，弹框消失，重新刷新页面，
            message.success(res.data.msg);
            //注意：这里需要进行沟通，删除成功后到首页还是当前页
            //这里删除成功后返回到第一页
            this.setState({
                offset:0
            },() => {
                this.getArticles();
            })
            
            
        }).catch((err) => {
            // console.log(err);
            message.success(err)

        }).finally(() => {
            //请求完成时执行的回调函数
            this.setState({
                deleteArticleConfirmLoading:false,  //加载消失
                isShowArticleModal:false   //弹窗消失
            })
        })

    }
   

    //获取文章列表信息
    getArticles = () => {
        this.setState({
            isLoading: true
        })
        getDataList(this.state.offset, this.state.limited)
            .then(res => {
                // console.log(res.data)
                // console.log(res.data.list)
                const columnsKeys = Object.keys(res.data.list[0]);
                // console.log(columnsKeys);
                const columns = createColumns(columnsKeys);
                columns.push({
                    title : '操作',
                    key: 'actions',
                    render: (text, record, index) => {
                        return (
                            <ButtonGroup>
                                <Button size="small">
                                    {/* 点击编辑后进行路由的跳转 */}
                                    <NavLink to={`/admin/article/edit:${record.id}`}>编辑</NavLink>
                                </Button>
                                <Button size="small" onClick={this.showDeleteArticleModal.bind(this,record)}>删除</Button>
                            </ButtonGroup>
                        )
                    }
                })
                //如果请求完成之后组件已经销毁，就不用设置state
                if(!this.updater.isMounted(this)) return;
                this.setState({
                    total: res.data.total,
                    list: res.data.list,
                    columns : columns,
                })
            })
            .catch(err => {
                //处理错误
            })
            .finally(() =>{
                if(!this.updater.isMounted(this)) return;
                this.setState({
                    isLoading: false
                })
            })
    }

    //页面发生变化触发的函数
    onPageChange = (page, pageSize) =>{
        // console.log(page, pageSize);   //page 表示是第几页，pageSize表示每一页有多少条数据
        this.setState({
            offset: pageSize*(page-1),
            limited: pageSize
        },() => {
            this.getArticles()
        })
    }

    //每页展示多少条所触发的函数
    onShowSizeChange = (current, size)=>{
        //console.log(current, size);   //current指向当前页，zise表示每页多少条数据
        //当改变每页的数据量时，应该留在当前页还是回到第一页
        //当改变每页数据量时，跳到首页
    }
    
    toExcel = () => {
        //在实际的项目中，实际上是前端发送一个Ajax请求到后端，然后后端发送一个文件下载地址
        //但在这里简单实现一下，将当前也存为excel表格进行返回
        console.log('toExcel');
        exportExcel(this.state.list);
    }

    //新建文章

    //类组件的生命周期函数
    componentDidMount(){
        // console.log(this.updater.isMounted(this));
        this.getArticles();

    }
    render() {
        let {isLoading, total, offset, limited, deleteArticleTitle,isShowArticleModal,deleteArticleConfirmLoading} = this.state;
        return (
            <Card
                title="文章列表页面"
                bordered={false}
                // style={{ width: '100%', height: 480}}
                className="YTCard"
                extra={[
                // <Button onClick={this.newFile} key='1' style={{margin: 5}}>
                //     <NavLink to={`/admin/article/edit:1111111111111111`}>新建文章</NavLink>
                // </Button>,
                <Button onClick={this.toExcel} key='2'>导出excel</Button>
            ]}
            >
                <Table
                    rowKey={record => record.id}
                    dataSource={this.state.list}
                    columns={this.state.columns}
                    loading={isLoading}
                    pagination={{
                        current: offset/limited + 1,
                        total: total,
                        hideOnSinglePage: true,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        onShowSizeChange:this.onShowSizeChange,
                        onChange: this.onPageChange,
                        pageSizeOptions: ['10','15','20','30'],
        
                    }}
                />
                <Modal 
                    title='此操作不可逆，请谨慎?'
                    visible={isShowArticleModal}   
                    onCancel={this.hideDeleteModal}
                    maskClosable={false}
                    confirmLoading={deleteArticleConfirmLoading}
                    onOk={this.deleteArticle}
                    
                >
                    <Typography>确定要删除<span style={{color:'#f00'}}>{deleteArticleTitle}</span>吗？</Typography>
                </Modal>
            </Card>
        )
    }


}

export default ArticleList;